package cn.iocoder.yudao.module.shop.service.masterstatistics;

import cn.iocoder.yudao.module.shop.config.OrderFeedbackConfig;
import cn.iocoder.yudao.module.shop.dal.dataobject.jiucase.ShopJiuCaseDO;
import cn.iocoder.yudao.module.shop.dal.dataobject.order.ShopOrderDO;
import cn.iocoder.yudao.module.shop.dal.dataobject.orderfeedback.ShopOrderFeedbackDO;
import cn.iocoder.yudao.module.shop.service.order.ShopOrderItemService;
import cn.iocoder.yudao.module.shop.service.order.dto.ShopOrderItemHandleDTO;
import cn.iocoder.yudao.module.system.api.user.AdminUserApi;
import cn.iocoder.yudao.module.system.api.user.dto.AdminUserRespDTO;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;

import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import java.util.*;
import cn.iocoder.yudao.module.shop.controller.admin.masterstatistics.vo.*;
import cn.iocoder.yudao.module.shop.dal.dataobject.masterstatistics.ShopMasterStatisticsDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;

import cn.iocoder.yudao.module.shop.convert.masterstatistics.ShopMasterStatisticsConvert;
import cn.iocoder.yudao.module.shop.dal.mysql.masterstatistics.ShopMasterStatisticsMapper;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.shop.enums.ErrorCodeConstants.*;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.ListUtil;

/**
 * 艾灸师统计 Service 实现类
 *
 * @author 曹建伟
 */
@Service
@Validated
public class ShopMasterStatisticsServiceImpl implements ShopMasterStatisticsService {

    @Resource
    private ShopMasterStatisticsMapper masterStatisticsMapper;

    @Resource
    private AdminUserApi adminUserApi;

    @Resource
    private ShopOrderItemService shopOrderItemService;

    @Override
    public Long createMasterStatistics(ShopMasterStatisticsCreateReqVO createReqVO) {
        // 插入
        ShopMasterStatisticsDO masterStatistics = ShopMasterStatisticsConvert.INSTANCE.convert(createReqVO);
        masterStatisticsMapper.insert(masterStatistics);
        // 返回
        return masterStatistics.getId();
    }

    @Override
    public void updateMasterStatistics(ShopMasterStatisticsUpdateReqVO updateReqVO) {
        // 校验存在
        validateMasterStatisticsExists(updateReqVO.getId());
        // 更新
        ShopMasterStatisticsDO updateObj = ShopMasterStatisticsConvert.INSTANCE.convert(updateReqVO);
        masterStatisticsMapper.updateById(updateObj);
    }

    @Override
    public void deleteMasterStatistics(Long id) {
        // 校验存在
        validateMasterStatisticsExists(id);
        // 删除
        masterStatisticsMapper.deleteById(id);
    }

    private void validateMasterStatisticsExists(Long id) {
        if (masterStatisticsMapper.selectById(id) == null) {
            throw exception(MASTER_STATISTICS_NOT_EXISTS);
        }
    }

    @Override
    public ShopMasterStatisticsDO getMasterStatistics(Long id) {
        return masterStatisticsMapper.selectById(id);
    }

    @Override
    public List<ShopMasterStatisticsDO> getMasterStatisticsList(Collection<Long> ids) {
        if (CollUtil.isEmpty(ids)) {
            return ListUtil.empty();
        }
        return masterStatisticsMapper.selectBatchIds(ids);
    }

    @Override
    public PageResult<ShopMasterStatisticsDO> getMasterStatisticsPage(ShopMasterStatisticsPageReqVO pageReqVO) {
        return masterStatisticsMapper.selectPage(pageReqVO);
    }

    @Override
    public List<ShopMasterStatisticsDO> getMasterStatisticsList(ShopMasterStatisticsExportReqVO exportReqVO) {
        return masterStatisticsMapper.selectList(exportReqVO);
    }

    private ShopMasterStatisticsDO get(Long masterId){
        ShopMasterStatisticsDO statisticsDO = masterStatisticsMapper.selectOne(ShopMasterStatisticsDO::getUserId, masterId);

        return statisticsDO;
    }

    @Transactional(rollbackFor = Exception.class)
    private ShopMasterStatisticsDO getOrCreate(Long masterId){
        ShopMasterStatisticsDO statisticsDO = masterStatisticsMapper.selectOne(ShopMasterStatisticsDO::getUserId, masterId);
        if(statisticsDO == null){
            statisticsDO = new ShopMasterStatisticsDO();

            AdminUserRespDTO master = adminUserApi.getUser(masterId);

            if(master == null){
                throw  exception(MASTER_STATISTICS_NOT_FIND_MASTER);
            }

            statisticsDO.setUserId(masterId);
            statisticsDO.setTotalCount(0);
            statisticsDO.setTotalTimes(0);
            statisticsDO.setTotalJiucase(0);

            statisticsDO.setDefaultFeedbackCount(0);
            statisticsDO.setConfirmedFeedbackCount(0);
            statisticsDO.setBalanceScore(0);
            statisticsDO.setSkillScore(0);
            statisticsDO.setServiceScore(0);
            statisticsDO.setResultScore(0);

            statisticsDO.setFirstChargeCount(0);
            statisticsDO.setFirstChargePrice(0);

            statisticsDO.setTenantId(master.getTenantId());

            masterStatisticsMapper.insert(statisticsDO);
        }

        return statisticsDO;
    }

    @Override
    public void recordOrder(ShopOrderDO shopOrderDO){
        ShopMasterStatisticsDO statisticsDO = getOrCreate(shopOrderDO.getUserId());
        ShopOrderItemHandleDTO handleDTO = shopOrderItemService.getHandleByOrderId(shopOrderDO.getId());
        statisticsDO.setTotalCount(statisticsDO.getTotalCount() + handleDTO.getHandleCount());
        statisticsDO.setTotalTimes(statisticsDO.getTotalTimes() + 1);
        statisticsDO.setTotalCount(statisticsDO.getTotalCount() + 1);

        masterStatisticsMapper.updateById(statisticsDO);
    }

    @Override
    public void rollbackOrder(ShopOrderDO order){
        ShopMasterStatisticsDO statisticsDO = get(order.getUserId());
        if(statisticsDO == null){
            return;
        }

        ShopOrderItemHandleDTO handleDTO = shopOrderItemService.getHandleByOrderId(order.getId());
        statisticsDO.setTotalCount(statisticsDO.getTotalCount() - handleDTO.getHandleCount());
        statisticsDO.setTotalTimes(statisticsDO.getTotalTimes() - 1);
        statisticsDO.setTotalCount(statisticsDO.getTotalCount() - 1);

        masterStatisticsMapper.updateById(statisticsDO);
    }

    //注意调用顺序
    @Override
    public void recordFeedback(ShopOrderFeedbackDO feedbackDO){
        ShopMasterStatisticsDO statisticsDO = getOrCreate(feedbackDO.getMasterId());

        if(feedbackDO.getConfirmed()){
            //创建的时候 会加一个默认值，确认的时候 要给减去，然后用打分的值
            statisticsDO.setBalanceScore(statisticsDO.getBalanceScore() - OrderFeedbackConfig.balanceScore);
            statisticsDO.setSkillScore(statisticsDO.getSkillScore() - OrderFeedbackConfig.skillScore);
            statisticsDO.setServiceScore(statisticsDO.getServiceScore() - OrderFeedbackConfig.serviceScore);
            statisticsDO.setResultScore(statisticsDO.getResultScore() - OrderFeedbackConfig.resultScore);

            statisticsDO.setConfirmedFeedbackCount(statisticsDO.getConfirmedFeedbackCount() + 1);
            statisticsDO.setDefaultFeedbackCount(statisticsDO.getDefaultFeedbackCount() - 1);
        }else{
            statisticsDO.setDefaultFeedbackCount(statisticsDO.getDefaultFeedbackCount() + 1);
        }

        statisticsDO.setBalanceScore(statisticsDO.getBalanceScore() + feedbackDO.getBalanceScore());
        statisticsDO.setSkillScore(statisticsDO.getSkillScore() + feedbackDO.getSkillScore());
        statisticsDO.setServiceScore(statisticsDO.getServiceScore() + feedbackDO.getServiceScore());
        statisticsDO.setResultScore(statisticsDO.getResultScore() + feedbackDO.getResultScore());

        masterStatisticsMapper.updateById(statisticsDO);
    }

    @Override
    public void recordFirstCharge(Long masterId, Integer count, Integer payPrice){
        ShopMasterStatisticsDO statisticsDO = getOrCreate(masterId);

        statisticsDO.setFirstChargeCount(statisticsDO.getFirstChargeCount() + count);
        statisticsDO.setFirstChargePrice(statisticsDO.getFirstChargePrice() + payPrice);

        masterStatisticsMapper.updateById(statisticsDO);
    }

    @Override
    public void recordJiucase(ShopJiuCaseDO caseDO){
        ShopMasterStatisticsDO statisticsDO = getOrCreate(caseDO.getUserId());

        statisticsDO.setTotalJiucase(statisticsDO.getTotalJiucase()+ 1);

        masterStatisticsMapper.updateById(statisticsDO);
    }

}
